<?php

namespace App\Console\Commands\Feishu\Hire;

use App\Library\FeiShu\SendFs;
use App\Models\Common\ConfigModel;
use App\Models\Feishu\FeishuHireApplicationModel;
use Carbon\Carbon;
use GuzzleHttp\Client;
use GuzzleHttp\Psr7\Request;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use PHPUnit\Util\Exception;

class HireSendNotifyCheckCookieCommand extends Command
{

    protected $signature = 'feishu:hire-send-notify-check-cookie';

    protected $description = '飞书:招聘简历记录周/月推送';

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle(): int
    {
        $todayStartAt = Carbon::now()->startOfDay()->getTimestamp();
        $todayEndAt   = Carbon::now()->startOfDay()->getTimestamp();

        try {
            // 今日数据
            self::getFsHireData($todayStartAt, $todayEndAt)['data'];
        } catch (\Exception $exception) {
            SendFs::newRobot()->setTitleContent('招聘报表获取数据失败', '请检查 Cookie !!!!', 'fea66474')->send();
            throw new Exception("招聘数据获取失败, Cookie 失效了");
        }

        return 1;
    }

    private function getFsHireData(int $startAt, int $endAt)
    {
        $config = ConfigModel::query()
                             ->where('module', 'guanyuanDB')
                             ->where('name', 'like', 'feishuHire%')
                             ->first();
        $cookie = $config->value;

        $client  = new Client();
        $headers = [
            'authority'          => 'onepiece-group.feishu.cn',
            'accept'             => 'application/json, text/plain, */*',
            'accept-language'    => 'zh-CN',
            'cache-control'      => 'no-cache',
            'content-type'       => 'application/json',
            'cookie'             => $cookie,
            'origin'             => 'https://onepiece-group.feishu.cn',
            'pragma'             => 'no-cache',
            'referer'            => 'https://onepiece-group.feishu.cn/hire/reports/7220708263875182595/widgets/7220708263879245827',
            'sec-ch-ua'          => '"Chromium";v="106", "Google Chrome";v="106", "Not;A=Brand";v="99"',
            'sec-ch-ua-mobile'   => '?0',
            'sec-ch-ua-platform' => '"macOS"',
            'sec-fetch-dest'     => 'empty',
            'sec-fetch-mode'     => 'cors',
            'sec-fetch-site'     => 'same-origin',
            'user-agent'         => 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/106.0.0.0 Safari/537.36',
            'x-csrf-token'       => '5bnMvDxCyVai_OhlCEqXS1FrVE8NZlFYKJX2_-iIJIc',
            'x-requested-with'   => 'XMLHttpRequest'
        ];
        $body    = '{
  "withAmount": true,
  "reportKey": "7220708263875182595",
  "reportType": "user",
  "widgetKey": "7220708263879245827",
  "measures": [
    {
      "data": null,
      "key": "HrName",
      "rawKey": "HrName"
    },
    {
      "data": null,
      "key": "appliCount",
      "rawKey": "appliCount"
    },
    {
      "data": null,
      "key": "interviewRound1Scheduled",
      "rawKey": "interviewRound1Scheduled"
    },
    {
      "data": null,
      "key": "appOfferSend",
      "rawKey": "appOfferSend"
    }
  ],
  "dimensions": [
    {
      "key": "hr"
    }
  ],
  "orders": [],
  "filters": {
    "values": {
      "jobProcess": [
        "6977190259583453476"
      ],
      "jobRange": [
        "all"
      ],
      "jobStatus": [
        "1"
      ],
      "operationTime": [
        "' . ($startAt * 1000) . '",
        "' . ($endAt * 1000) . '"
      ]
    },
    "meta": []
  },
  "withSum": true,
  "showZeroRow": false,
  "shareOwnerData": 1,
  "fromReportKey": "7220708263875182595",
  "limit": 50,
  "offset": 0
}';
        $request = new Request('POST',
            'https://onepiece-group.feishu.cn/atsx/api/report/selfhelp/widget/data?type=table', $headers, $body);
        $res     = $client->sendAsync($request)->wait();
        $data    = $res->getBody();
        return json_decode($data, 1);

    }

}
